/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.security.service

import cn.hutool.core.util.RandomUtil
import jakarta.annotation.Resource
import me.zhengjie.common.utils.RedisUtil
import me.zhengjie.modules.security.config.bean.LoginProperties
import me.zhengjie.modules.security.service.dto.JwtUserDto
import org.springframework.beans.factory.annotation.Value
import org.springframework.scheduling.annotation.Async
import org.springframework.stereotype.Component
import org.apache.commons.lang3.StringUtils
/**
 * @author Zheng Jie
 * @description 用户缓存管理
 * @date 2022-05-26
 */
@Component
class UserCacheManager (
    //@Resource
    private val redisUtils: RedisUtil? = null,

    @Value("\${login.user-cache.idle-time}")
    private val idleTime: Long = 0
){
    /**
     * 返回用户缓存
     * @param userName 用户名
     * @return JwtUserDto
     */
    fun getUserCache(userName: String): JwtUserDto? {
        if (StringUtils.isNotEmpty(userName)) {
            // 获取数据
            val obj: Any = redisUtils!!.get(LoginProperties.cacheKey + userName)!!
            if (obj != null) {
                return obj as JwtUserDto
            }
        }
        return null
    }

    /**
     * 添加缓存到Redis
     * @param userName 用户名
     */
    @Async
    fun addUserCache(userName: String, user: JwtUserDto?) {
        if (StringUtils.isNotEmpty(userName)) {
            // 添加数据, 避免数据同时过期
            val time = idleTime + RandomUtil.randomInt(900, 1800)
            redisUtils!!.set(LoginProperties.cacheKey + userName, user!!, time)
        }
    }

    /**
     * 清理用户缓存信息
     * 用户信息变更时
     * @param userName 用户名
     */
    @Async
    fun cleanUserCache(userName: String) {
        if (StringUtils.isNotEmpty(userName)) {
            // 清除数据
            redisUtils!!.del(LoginProperties.cacheKey + userName)
        }
    }
}